<?php
//检查今天到期和即将到期的品牌发通知（每天上午10点）
ini_set('display_errors', 1);
error_reporting(-1);
require_once '/data/wwwroot/g_vendor/autoload.php';

use Biz\model\brand\Brand as mBrand;
use Biz\model\brand\BrandOrder;
use Biz\model\brandAccount\BrandAccountAuth;
use Biz\model\brandAccount\BrandAccountInfo;
use Biz\service\brandAccount\BrandAccount;
use Doraemon\cache\Queue;
use Doraemon\service\DingTalkAlert;
use Doraemon\tools\HhzEnv;
use Doraemon\tools\Log;
use Doraemon\tools\Sms;

todayExpired();
willExpired();
willExpiredBrandRemaind();
checkNotInAccount();

function todayExpired()
{
    var_dump('今天到期的品牌');
//今天到期的品牌
    $where = [
        'type' => BrandAccountInfo::ACCOUNT_TYPE_BRAND,
        'account_status' => BrandAccountInfo::ACCOUNT_STATUS_EXPIRE,
        'in_end_time' => date('Y-m-d', strtotime('-1 days'))
    ];
    $accountList = BrandAccountInfo::getAllByWhere($where);
    if ($accountList) {
        foreach ($accountList as $account) {
            var_dump('品牌信息', [
                'account_id' => $account['id'],
                'uid' => $account['uid'],
                'nick' => $account['nick'],
                'brand_id' => $account['brand_id'],
                'in_start_time' => $account['in_start_time'],
                'in_end_time' => $account['in_end_time']
            ]);
            expireMsg($account, '品牌已过期', 1);
            remindBrand($account, 1);
        }
    }
}

function willExpired()
{
    var_dump('45天后到期的品牌');
//45天后到期的品牌
    $where = [
        'type' => BrandAccountInfo::ACCOUNT_TYPE_BRAND,
        'account_status' => BrandAccountInfo::ACCOUNT_STATUS_USED,
        'in_end_time' => date('Y-m-d', strtotime('+45day'))
    ];
    $accountList = BrandAccountInfo::getAllByWhere($where);
    if ($accountList) {
        $uids = array_column($accountList, 'uid');
        $hasUnUsedOrderRes = BrandOrder::hasUnUsedOrder($uids);
        foreach ($accountList as $account) {
            if (!$hasUnUsedOrderRes[$account['uid']]) {
                expireMsg($account, '品牌即将到期(45天)', 2);
            }
        }
    }
}

function willExpiredBrandRemaind()
{
    var_dump('60天后到期的品牌');
//60天后到期的品牌
    $where = [
        'type' => BrandAccountInfo::ACCOUNT_TYPE_BRAND,
        'account_status' => BrandAccountInfo::ACCOUNT_STATUS_USED,
        'in_end_time' => date('Y-m-d', strtotime('+' . BrandAccount::AUTH_LAST_DAY . 'day'))
    ];
    $accountList = BrandAccountInfo::getAllByWhere($where);
    if ($accountList) {
        $uids = array_column($accountList, 'uid');
        $hasUnUsedOrderRes = BrandOrder::hasUnUsedOrder($uids);
        foreach ($accountList as $account) {
            if (!$hasUnUsedOrderRes[$account['uid']]) {
                remindBrand($account, 2);
            }
        }
    }
}

function expireMsg($accountInfo, $title, $type = 1)
{
    if (HhzEnv::isTest() || HhzEnv::isGray()) {
        return false;
    }
    $brandId = $accountInfo['brand_id'];
    $uid = $accountInfo['uid'];
    $nick = $accountInfo['nick'];
    $brandInfo = mBrand::getByWhere(['id' => $brandId]);
    $brandName = $brandInfo['brand_name'];
    $startTime = $accountInfo['in_start_time'];
    $endTime = $accountInfo['in_end_time'];

    $msg = <<<MSG
## {$title}
- 品牌ID: **{$brandId}**
- 品牌名称: **{$brandName}**
- 用户UID: **{$uid}** 
- 用户昵称: **{$nick}**
- 入驻时间：**{$startTime} - {$endTime}**
### 过期时间【{$endTime}】请及时关注
MSG;

    DingTalkAlert::sendMarkdownMsg(DingTalkAlert::BRAND_EXPIRE_KEY, $title, $msg, true);
}

function remindBrand($accountInfo, $type = 1)
{
    $uid = $accountInfo['uid'];
    $authList = BrandAccountAuth::getAllByWhere([
        'account_id' => $accountInfo['id'],
        'phone[!]' => '',
        'auth_status[!]' => BrandAccountAuth::AUTH_STATUS_DEL,
        'ORDER' => ['id' => 'DESC']
    ]);
    $usedPhone = '';
    $passPhone = '';
    $normalPhone = '';
    foreach ($authList as $row) {
        if ($row['auth_status'] == BrandAccountAuth::AUTH_STATUS_USED && !$usedPhone) {
            $usedPhone = $row['phone'];
        } else if ($row['auth_status'] == BrandAccountAuth::AUTH_STATUS_PASS && !$passPhone) {
            $passPhone = $row['phone'];
        } else if (!$normalPhone) {
            $normalPhone = $row['phone'];
        }
    }
    $phone = $usedPhone ? $usedPhone : ($passPhone ? $passPhone : $normalPhone);

    if ($type == 1) {//已到期
        $msgInfo = [
            'send_user' => 6587838,
            'con_type' => 0,
            'content' => json_encode([
                'con' => '尊敬的商家，您的认证账号已到期，如您想重新获取账号权益，请前往电脑端的好好住官网haohaozhu.com品牌入驻页补充认证信息。',
            ])
        ];
        Queue::insertQueue('queue/im/send', [
            'to_uids' => [$uid],
            'msgInfo' => $msgInfo
        ], Queue::QUEUE_DORAEMON);

        //$msg = '【好好住】您的认证账号已到期，如果想要重新获取权益，请通过电脑端访问好好住官网www.haohaozhu.cn在品牌入驻页补充认证信息';
        $smsReason = '已到期，如果想要重新获取权益，';
    } else {//即将到期
        $msgInfo = [
            'send_user' => 6587838,
            'con_type' => 0,
            'content' => json_encode([
                'con' => '尊敬的商家，您的认证账号即将到期，为了保证您的权益，请及时前往电脑端的好好住官网haohaozhu.com品牌入驻页补充认证信息。',
            ])
        ];
        Queue::insertQueue('queue/im/send', [
            'to_uids' => [$uid],
            'msgInfo' => $msgInfo
        ], Queue::QUEUE_DORAEMON);
        // $msg = '【好好住】尊敬的商家，您的认证账号即将到期，为了保证您的权益，请及时前往电脑端的好好住官网haohaozhu.com品牌入驻页补充认证信息。';
        $smsReason = '即将到期，为了保证您的权益，';
    }
    if ($phone && $smsReason) {
        Sms::sendSms(
            $phone,
            ['reason' => $smsReason],
            ['CnUnicom' => Sms::CHINA_UNICOM_CONFIG['temp_brand_expired'], 'aliyun' => Sms::TYPE_BRAND_EXPIRED],
            '86'
        );
    }
}

function checkNotInAccount()
{
    var_dump('3个月以上仍未入驻的品牌');
    $accountList = BrandAccountInfo::getAllByWhere([
        'account_status' => BrandAccountInfo::ACCOUNT_STATUS_DEFAULT,
        'edit_time[<=]' => date('Y-m-d', strtotime('-3 month'))
    ]);
    var_dump(BrandAccountInfo::log());
    var_dump('账户数量：' . count($accountList), BrandAccountInfo::log());
    $accountIds = array_column($accountList, 'id');
    $accountList = array_column($accountList, null, 'id');
    foreach ($accountList as $row) {
        BrandAccountInfo::updateData([
            'account_status' => BrandAccountInfo::ACCOUNT_STATUS_EXPIRE,
            'auth_status' => BrandAccountInfo::AUTH_STATUS_EXPIRE,
            'brand_type' => mBrand::BRAND_TYPE_EXPIRE,
        ],
            ['id' => $row['id'], 'account_status' => BrandAccountInfo::ACCOUNT_STATUS_DEFAULT]
        );
    }
    $authList = $accountIds ? BrandAccountAuth::getAllByWhere(['auth_status' => BrandAccountAuth::AUTH_STATUS_PASS, 'account_id' => $accountIds]) : [];
    var_dump('认证信息通过的数量:' . count($authList));
    foreach ($authList as $row) {
        $accountId = $row['account_id'];
        $accountInfo = $accountList[$accountId];
        $uid = $accountInfo['uid'];
        $isOperate = false;
        if ($accountInfo['type'] == BrandAccountInfo::ACCOUNT_TYPE_SHOP) {
            $isOperate = true;
        } else if ($accountInfo['type'] == BrandAccountInfo::ACCOUNT_TYPE_BRAND) {
            $hasUnUsedOrderRes = BrandOrder::hasUnUsedOrder($uid);
            $hasUnUsedOrder = $hasUnUsedOrderRes[$uid];
            //检查有没有待生效待的订单
            $isOperate = $hasUnUsedOrder ? false : true;
        }
        if ($isOperate) {
            var_dump('超过三个月，还未付款的账户和认证状态给置为过期', ['account_info' => $accountInfo, 'auth_info' => $row]);
            Log::info('超过三个月，还未付款的账户和认证状态给置为过期', ['account_info' => $accountInfo, 'auth_info' => $row]);
            BrandAccountAuth::updateData(['auth_status' => BrandAccountAuth::AUTH_STATUS_EXPIRE],
                ['id' => $row['id'], 'account_id' => $accountId, 'auth_status' => BrandAccountAuth::AUTH_STATUS_PASS]
            );
            var_dump('account auth sql', BrandAccountAuth::log());
        }
    }
}